#include "myrequesthandler.h"
#include <QByteArray>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include "response.h"
#include "util.h"

MyRequestHandler::MyRequestHandler(QObject* parent): HttpRequestHandler(parent)
{
    Q_UNUSED(parent)
	codec = QTextCodec::codecForName("UTF-8");
    QSettings conf("util-conf.ini", QSettings::IniFormat);
   
    bot = new Bot("XZ-BOT");
    bot->trainer("aiml/startup.xml");
}

void MyRequestHandler::service(HttpRequest &request, HttpResponse &response)
{
    
    QByteArray path=request.getPath();
    if (path == "/api/v1/bot") {
        ResponseBot(request, response);
    }else if (path == "/api/v1/keys"){
        ResponseKeys(request, response);
    }else if (path == "/api/v1/patterns") {
        ResponsePatterns(request, response);
    }else if (path == "/api/v1/contacts") {
        ResponseContacts(request, response);
    }else {
		QByteArray content = request.getBody();
		qDebug()<<"body:" <<content;
        response.setHeader("Content-Type", "application/json; charset=utf-8");
        Response res;
        res.setCode("4000");
        QList<Response::resultStruct> list;
        Response::resultStruct temp;
        temp.resultType = "text";
        temp.content = content;
        list.append(temp);
        res.setResultList(list);
        response.write(res.toJson().toUtf8());
    }
   
}

void MyRequestHandler::ResponseBot(HttpRequest& request, HttpResponse& response)
{
    response.setHeader("Content-Type", "application/json; charset=utf-8");
    Response res;
    QByteArray content = request.getBody();
    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(content, &json_error));

    if (json_error.error != QJsonParseError::NoError) {

        res.setCode("4001");
        QList<Response::resultStruct> list;
        Response::resultStruct temp;
        temp.resultType = "text";
        temp.content = codec->toUnicode("无法解析的JSON");
        list.append(temp);
        res.setResultList(list);
        response.write(res.toJson().toUtf8());

        return;
    }

    QJsonObject obj = jsonDoc.object();
    if (obj.contains("text")) {

        QString text = obj.value("text").toString();

        if (text.isEmpty()) {
            res.setCode("4002");
            QList<Response::resultStruct> list;
            Response::resultStruct temp;
            temp.resultType = "text";
            temp.content = codec->toUnicode("Text 为空!");
            list.append(temp);
            res.setResultList(list);
            response.write(res.toJson().toUtf8());
            return;
        }

        QList<Response::resultStruct> rep = bot->get_response(text);
        res.setCode("200");
        res.setResultList(rep);
        response.write(res.toJson().toUtf8());
        return;

    }

    res.setCode("5000");
    QList<Response::resultStruct> list;
    Response::resultStruct temp;
    temp.resultType = "text";
    temp.content =codec->toUnicode("未知的错误!");
    list.append(temp);
    res.setResultList(list);
    response.write(res.toJson().toUtf8());


}

void MyRequestHandler::ResponseKeys(HttpRequest& request, HttpResponse& response)
{
    response.setHeader("Content-Type", "application/json; charset=utf-8");
    Response res;
    QByteArray content = request.getBody();
    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(content, &json_error));

    if (json_error.error != QJsonParseError::NoError) {

        res.setCode("4001");
        QList<Response::resultStruct> list;
        Response::resultStruct temp;
        temp.resultType = "text";
        temp.content = codec->toUnicode("无法解析的JSON!");
        list.append(temp);
        res.setResultList(list);
        response.write(res.toJson().toUtf8());

        return;
    }

    QJsonObject obj = jsonDoc.object();
    if (obj.contains("userinfo")) {

        res.setCode("200");
        QList<Response::resultStruct> list;
        Response::resultStruct temp;
        temp.resultType = "text";
        QStringList keys = bot->getPatternKeys();
        QString _string  = keys.join(",");
        temp.content = _string;
        list.append(temp);
        res.setResultList(list);
        response.write(res.toJson().toUtf8());

        return;
    }

    

    res.setCode("5000");
    QList<Response::resultStruct> list;
    Response::resultStruct temp;
    temp.resultType = "text";
    temp.content =codec->toUnicode("未知的错误!") ;
    list.append(temp);
    res.setResultList(list);
    response.write(res.toJson().toUtf8());


}

void MyRequestHandler::ResponsePatterns(HttpRequest& request, HttpResponse& response)
{

    response.setHeader("Content-Type", "application/json; charset=utf-8");
    Response res;
    QByteArray content = request.getBody();
    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(content, &json_error));

    if (json_error.error != QJsonParseError::NoError) {

        res.setCode("4001");
        QList<Response::resultStruct> list;
        Response::resultStruct temp;
        temp.resultType = "text";
        temp.content = codec->toUnicode("无法解析的JSON!");
        list.append(temp);
        res.setResultList(list);
        response.write(res.toJson().toUtf8());

        return;
    }

    QJsonObject obj = jsonDoc.object();
    if (obj.contains("userinfo") && obj.contains("text")) {
        QString key = obj.value("text").toString();
        res.setCode("200");
        QList<Response::resultStruct> list;
        Response::resultStruct temp;
        temp.resultType = "text";
        QStringList patterns = bot->findPatterns(key);
        QString _string = patterns.join(",");
        temp.content = _string;
        list.append(temp);
        res.setResultList(list);
        response.write(res.toJson().toUtf8());

        return;
    }


    res.setCode("5000");
    QList<Response::resultStruct> list;
    Response::resultStruct temp;
    temp.resultType = "text";
    temp.content = codec->toUnicode("未知的错误!");
    list.append(temp);
    res.setResultList(list);
    response.write(res.toJson().toUtf8());
}

void MyRequestHandler::ResponseContacts(HttpRequest& request, HttpResponse& response)
{

    response.setHeader("Content-Type", "application/json; charset=utf-8");
    Response res;
    QByteArray content = request.getBody();
    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(content, &json_error));

    if (json_error.error != QJsonParseError::NoError) {

        res.setCode("4001");
        QList<Response::resultStruct> list;
        Response::resultStruct temp;
        temp.resultType = "text";
        temp.content = codec->toUnicode("无法解析的JSON!");
        list.append(temp);
        res.setResultList(list);
        response.write(res.toJson().toUtf8());

        return;
    }

    QJsonObject obj = jsonDoc.object();
    if (obj.contains("contacts")){
        
		//处理数据
		Util::toCSVFile(obj);
		//应答
        res.setCode("200");
        QList<Response::resultStruct> list;
        Response::resultStruct temp;
        temp.resultType = "text";
        temp.content = QString("OK");
        list.append(temp);
        res.setResultList(list);
        response.write(res.toJson().toUtf8());

        return;
    }


    res.setCode("5000");
    QList<Response::resultStruct> list;
    Response::resultStruct temp;
    temp.resultType = "text";
    temp.content = codec->toUnicode("未知的错误!");
    list.append(temp);
    res.setResultList(list);
    response.write(res.toJson().toUtf8());
}

